package com.cqqec.boot.controller;

import com.cqqec.boot.entity.Dish;
import com.cqqec.boot.service.DishService;
import com.cqqec.boot.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DishController {
    @Autowired
    private DishService dishService;
    @RequestMapping("/getList/{current}")
    public String getList(Model model, @PathVariable int current) {
        //构造分页对象
        PageUtil<Dish> page = dishService.getDishByLimit(current, 3);
        //将查询的数据放到model里面
        model.addAttribute("page", page);
        return "index";
    }

    /**
     * 修改
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/updateById/{id}")
    public String updateById(@PathVariable int id, Model model) {
        //根据id查询数据
        Dish dish = dishService.getDishById(id);
        model.addAttribute("dish", dish);
        return "update";
    }

    /**
     * 修改菜单
     * @param dish
     * @return
     */
    @PostMapping("/update")
    public String updateDish(Dish dish) {
        //获取要修改数据
        int count = dishService.updateDish(dish);
        if (count > 0) {
            return "redirect:/getList/1";//修改后跳转到列表页
        } else {
            return "update";//修改失败返回修改页面
        }
    }
    /**
     * 删除菜单
     */
    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable int id) {
        //根据id删除数据
        int count = dishService.deleteById(id);
        if (count > 0) {
            return "redirect:/getList/1";//删除后跳转到列表页
        } else {
            return "redirect:/getList/1";
        }
    }
    /**
     * 添加菜单
     */
    @PostMapping("/add")
    public String addDish(Dish dish) {
        //添加数据
        int count = dishService.addDish(dish);
        if (count > 0) {
            return "redirect:/getList/1";//添加后跳转到列表页
        } else {
            return "redirect:/add";//添加失败返回添加页面
        }
    }
    @GetMapping("/add")
    public String add(Model model) {
        return "add";
    }
    /**
     * 起售停售
     */
    @GetMapping("/updateStatus/{id}")
    public String updateStatus(@PathVariable int id) {
        //根据id查询数据
        Dish dish = dishService.getDishById(id);
        //判断菜品是否存在 null
        if (dish == null){
            return "redirect:/getList/1";//修改后跳转到列表页
        }
        //判断当前状态
        String currentStatus = dish.getStatus();
        if ("1".equals(currentStatus)) { // 使用常量在前的方式避免空指针异常
            dish.setStatus("0");
        } else {
            dish.setStatus("1");
        }
        //更新状态
        int count = dishService.updateStatus(dish);
        if (count > 0) {
            return "redirect:/getList/1";//修改后跳转到列表页
        } else {
            return "redirect:/getList/1";
        }
    }
}
